
//这里写每个路由对应的业务
const Database = require('../mongodb/index.js');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');

const { ObjectId } = require('mongodb');
const sendEmail = require('./utils/email.js');
const { getTime, getimg, getjwt, getYMDHMS } = require('./utils/index.js');
userCode = {}
userJwt = {}
module.exports = {
  async login (req, res) {
    const requser = req.body
    console.log(requser)
    const db = new Database();
    let user = null
    // 查询数据
    try {
      // // 连接数据库
      await db.connect();
      user = await db.findOne('users', { Username: requser.username });
      await db.disconnect();

    } catch (error) {
      res.send({ code: 500, message: "数据库异常!" })
    }
    if (!user) {
      res.send({ code: 403, message: "账号未注册!" })
      return
    }
    if (user.Password === requser.password) {
      // 签名token
      const secret = crypto.randomBytes(20).toString('hex');; // 应该是一个复杂的随机字符串
      userJwt[user._id] = secret
      const expiresIn = '1h'; // token有效时长
      const token = jwt.sign(user, secret, { expiresIn });
      res.send({
        code: 200, message: "登录成功!", data: {
          username: user.Username,
          token,
          Avatar: user.Avatar,
          userId: user._id,
          email: user.Email
        }
      })
      return
    } else {
      res.send({ code: 40001, message: "密码错误!" })
      return
    }
  },
  async sendEmail (req, res) {
    if (!req.body.email || req.body.email === '') {
      res.send({ code: 403, message: '请输入正确的邮箱!' })
      return
    }
    const number = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
    userCode[`${req.body.email}`] = number;
    sendEmail(req.body.email, userCode[req.body.email])
    setTimeout(() => {
      userCode[req.body.email] = ''
    }, 300000)
    res.send({ code: 200, message: '发送成功!' })
  },
  async register (req, res) {
    const user = req.body
    if (!user) return
    if (userCode[user.email] === '') {
      res.send({ code: 403, message: `验证码已过期!` })
      return
    }
    if (userCode[user.email] !== user.code) {
      res.send({ code: 40001, message: `验证码错误!` })
      return
    }
    const img = getimg()
    const db = new Database();
    let users = null
    // 查询数据
    try {
      // // 连接数据库
      await db.connect();
      users = await db.findOne('users', { Email: user.email });
      if (users) {
        res.send({ code: 403, message: "邮箱已被注册!" })
        return
      }
      // 插入数据
      const insertResult = await db.insertOne('users', {
        "Username": user.username,
        "Password": user.password,
        "Email": user.email,
        "Avatar": img,
        "CreationDate": getTime()
      });
      await db.disconnect();

    } catch (error) {
      res.send({ code: 500, message: "数据库异常!" })
      return
    }

    res.send({ code: 200, message: "注册成功" })
  }

}